
let goods = localStorage.getItem("goods")?JSON.parse(localStorage.getItem("goods")):[]

//获取数据
$.ajax({
    url:"http://localhost:3000/api",
    data:{
        type:"getGoods"
    },
    success:res=>{
        res = JSON.parse(res).data;
        //渲染页面
        renderGoods(res)
    }
})
$("#goodsNum").html(goods.length);
$(".list-goods").on("click",".add",function(){
    //获取id
    const id = $(this).attr("index")
    //获取现价
    const seles = $(this).prev().prev().children("i").html()-0;
    //根据id，添加购物车商品
    setLocal(id,seles);
    
}) 
function setLocal(id,seles){
    const goods = localStorage.getItem("goods")?JSON.parse(localStorage.getItem("goods")):[];
    if(goods.length<1){
        goods.push({
            id:id,
            num:1,
            flag:0,
            seles
        })
    }else{
        let i = 0;
        const flag = goods.some((val,idx)=>{
            i=idx;
            return val.id ===id;
        })
        if(flag){
            goods[i].num++;
        }else{
            goods.push({
                id:id,
                num:1,
                flag:0,
                seles
            })
        }
    }
    localStorage.setItem("goods",JSON.stringify(goods));
    $("#goodsNum").html(goods.length);
}

function renderGoods(res){
    let str = ""  
    res.forEach(val => {
        let imgstr = ""
        //小图片列表
        for(let i = 0;i<val.sImgs.length;i++){   
            imgstr+=`<img src="${val.sImgs[i]}" alt="">`
        }
        str+=`<div>
        <a href="./goodsDetail.html?id=${val.id}">
        <img src="${val.img}" alt=""></a>
        <aside>
            ${imgstr}
        </aside>
        <h6>${val.proName}
        </h6>
        <del>￥<b>${val.price}</b></del>
        <span>￥<i>${val.seles}</i></span>
        <p>月销${val.stock}</p>
        <em class="add" index="${val.id}" ></em>
        </div>`
    });
    $(".list-goods").html(str);  
}
